<template>
  <div
    class="carousel"
    @mouseenter="mouseEnter"
    @mouseleave='mouseLeave'
  >
    <!-- 父组件 -->
    <div class="inner">
      <CarDot
        :hasDot='hasDot'
        :itemLen='itemLen'
        :currentIndex='currentIndex'
        :dotBgColor='dotBgColor'
        @dotClick='dotClick'
      />
      <CarDirector
        :hasDirector='hasDirector'
        dir='prev'
        @dirClick='dirClick'
      />
      <CarDirector
        :hasDirector='hasDirector'
        dir='next'
        @dirClick='dirClick'
      />
      <slot></slot>
    </div>
  </div>
</template>

<script>
import {
  reactive,
  toRefs,
  onMounted,
  onBeforeUnmount,
  getCurrentInstance
} from 'vue'

import CarDot from './Dot'
import CarDirector from './Director'
export default {
  name: 'Carousel',
  components: {
    CarDot,
    CarDirector
  },
  props: {
    autoPlay: {
      type: Boolean,
      default: true
    },
    duration: {
      type: Number,
      default: 3000
    },
    initial: {
      type: Number,
      default: 0
    },
    hasDot: {
      type: Boolean,
      default: true
    },
    hasDirector: {
      type: Boolean,
      default: true
    },
    dotBgColor: {
      type: String
    }
  },
  setup (props) {
    const instance = getCurrentInstance()
    const state = reactive({
      currentIndex: props.initial,
      itemLen: 0
    })
    let timer = null;
    const autoPlay = () => {
      if (props.autoPlay) {
        timer = setInterval(() => {
          setIndex('next');
        }, props.duration)
      }
    }

    const setIndex = (dir) => {
      switch (dir) {
        case 'next':
          state.currentIndex += 1;
          if (state.currentIndex === state.itemLen) {
            state.currentIndex = 0;
          }
          break;
        case 'prev':
          state.currentIndex -= 1
          if (state.currentIndex === -1) {
            state.currentIndex = state.itemLen - 1;
          }
          break;
        default:
          break;
      }
    }

    const dotClick = (index) => {
      state.currentIndex = index;
    }

    const dirClick = (dir) => {
      console.log(1)
      setIndex(dir)
      console.log(1)
    }

    const mouseEnter = () => {
      _clearIntervalFn();
    }

    const mouseLeave = () => {
      autoPlay();
    }

    function _clearIntervalFn () {
      clearInterval(timer);
      timer = null;
    }

    onMounted(() => {
      state.itemLen = instance.slots.default()[0].children.length
      console.log(state)
      autoPlay()
    })

    onBeforeUnmount(() => {
      _clearIntervalFn()
    })
    return {
      ...toRefs(state),
      dotClick,
      dirClick,
      mouseEnter,
      mouseLeave
    }
  }
}
</script>

<style scoped>
  .carousel{
    width: 100%;
    height: 100%;
  }
  .inner{
    overflow:hidden;
    position:relative;
    width:100%;
    height:100%;
  }
</style>
